package rjeutsky.database.jdbc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

import rjeutsky.config.ConfigConstants;
import rjeutsky.database.interfaces.Repository;
import rjeutsky.models.User;
import rjeutsky.models.UserRole;

public class DatabaseInitializer {
	private Connection connection;
	
	public DatabaseInitializer(Connection connection) {
		this.connection = connection;
	}
	
	public void Initialize() throws FileNotFoundException, SQLException {
		String sql = getInitializationSql();
		Statement statement = connection.createStatement();
		statement.execute(sql);
		Repository repository = new JDBCRepository(connection);
		UserRole adminRole = new UserRole();
		adminRole.setName(UserRole.ADMIN);
		adminRole.setId(1L);
		repository.getUserRoleRepository().create(adminRole);
		User adminUser = new User();
		adminUser.setId(1L);
		adminUser.setLogin("admin");
		adminUser.setPassword("admin");
		adminUser.setSalt("");
		repository.getReaderRepository().create(adminUser);
		repository.addRoleToUser(adminUser, adminRole);
	}
	
	private String getInitializationSql () throws FileNotFoundException {
		StringBuilder builder = new StringBuilder();
		Scanner scanner = new Scanner(new InputStreamReader(new FileInputStream(new File(ConfigConstants.INIT_DB_SCRIPT))));
		while (scanner.hasNextLine()) {
			builder.append(scanner.nextLine() + "\n");
		}
		
		return builder.toString();
	}
}
